package cn.itsource.pethome_0310.basic.base;

import cn.hutool.core.util.StrUtil;
import cn.itsource.pethome_0310.basic.domain.BaseQuery;
import cn.itsource.pethome_0310.org.domain.Department;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.entity.Example;

import javax.persistence.Transient;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Objects;

public interface MybaseMapper<T extends MyBaseDomain> extends Mapper<T> {



     Class<T> getTClasss();
    /**
     * 抽取公共的逻辑删除接口
     * @param ids
     */
    default void batchDelete(List<Long> ids){
        //1.创建example 对象
        Example example = new Example(getTClasss());
        //2.创建条件语句对象
        example.createCriteria().andIn("id",ids);
        T t = null;
        try {
            t = getTClasss().newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        t.setDel(Boolean.FALSE);
        this.updateByExampleSelective(t,example);

    };
//    /**
//     * 抽取批量新增
//     */
//    default void batchInsert(List<T> ts){
//        ts.forEach(t -> this.insertSelective(t));
//    }


    /**
     * 这里做的是逻辑删除
     * @param id
     */
    default void delete(Long id){
        //1.创建example 对象
        Example example = new Example(getTClasss());
        //2.创建条件语句对象
        example.createCriteria().andEqualTo("id",id);
        T t = null;
        try {
            t = getTClasss().newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        t.setDel(Boolean.FALSE);
        this.updateByExampleSelective(t,example);

    }
    /**
     * 抽取公共的分页查询
     */
    default PageInfo findPageList(BaseQuery baseQuery){
        //1.分页
        PageHelper.startPage(baseQuery.getPage(),baseQuery.getRows());
        //2.高级条件查询
        List<T> ts = this.selectAll();
        return new PageInfo(ts);
    }

    default PageInfo findPageList1(BaseQuery baseQuery){
        //1.分页
        PageHelper.startPage(baseQuery.getPage(),baseQuery.getRows());
        //2.高级条件查询
        Example example = new Example(getTClasss());
        Example.Criteria criteria = example.createCriteria();
        //获取到当前对象所有的属性
        Field[] fields = getTClasss().getDeclaredFields();
        for (Field field : fields) {
            //这个方法是用来保利获取被private 修饰的字段或者方法
            field.setAccessible(true);
            Transient annotation = field.getAnnotation(Transient.class);
            if(Objects.nonNull(annotation)) continue;

            String name = field.getName();
            String type = field.getType().toString();
            if (type.contains("String")){
                if (StrUtil.isNotBlank(baseQuery.getKeyword()))
                    criteria.orLike(name,"%"+baseQuery.getKeyword()+"%");
            }

        }

        List<T> ts = this.selectByExample(example);
        return new PageInfo(ts);
    }
}
